package com.sunni.controller;

import com.sunni.entity.Student;
import com.sunni.repository.JDBC.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/thy")
public class ThymeleafController {

    @Resource(name = "jdbc_stuRep")
    private StudentRepository studentRepository;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student(1,"张三",22));
        list.add(new Student(2,"赵四",23));
        list.add(new Student(3,"王五",24));
        model.addAttribute("list",list);
        return "index";
    }

    /*
    * 常用语法
    * */
    @RequestMapping("/text")
    public String text(Model model){
        model.addAttribute("name","五五开");
        return "index";
    }

    @RequestMapping("/ifunless")
    public String ifunless(Model model){
        model.addAttribute("number",5);
        return "index";
    }


    @GetMapping("/each")
    public String each(Model model){
        List<Student> list = new ArrayList<>();
        list.add(new Student(1,"张三",22));
        list.add(new Student(2,"李四",23));
        list.add(new Student(3,"王五",24));
        model.addAttribute("list",list);
        return "index";
    }

//    url
    @RequestMapping("/getName")
    public String getName(Model model){
        model.addAttribute("name","五五开");
        return "index";
    }

    @GetMapping("/url/{name}")
    @ResponseBody
    public Object url(@PathVariable("name") String name){
        return name;
    }


    @RequestMapping("/src")
    public Object src(Model model){
        model.addAttribute("img_url","图片地址");
        return "index";
    }

//    查询所有
    @GetMapping("/jdbcfindall")
    public String stuFindAll(Model model){
        model.addAttribute("list",studentRepository.findAll());
        return "jdbc_test";
    }

//    增
    @PostMapping("/save")
    public String save(@RequestBody com.sunni.entity.JDBC.Student student){
        studentRepository.save(student);
        return "redirect:/thy/jdbcfindall";
    }

//    删
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        studentRepository.delete(id);
        return "redirect:/thy/jdbcfindall";
    }

//    改
    @GetMapping("/jdbcfindbyid/{id}")
    public String stuFindById(@PathVariable("id")Integer id, Model model){
        model.addAttribute("student",studentRepository.findById(id));
        return "jdbc_test";
    }
    @PostMapping("/update")
    public String update(@RequestBody com.sunni.entity.JDBC.Student student){
        System.out.println(student);
        studentRepository.update(student);
        return "redirect:/thy/jdbcfindall";
    }

}
